package org.ns.longhttp.pull;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

public class LongLoopClient implements AutoCloseable {
    CloseableHttpAsyncClient client;
    public LongLoopClient() {
        client = HttpAsyncClients.createDefault();
        client.start();

    }

    public static void main(String[] args){
        LongLoopClient client = new LongLoopClient();
        client.loop("http://localhost:11111/test", null, new ResponseCallback() {
            @Override
            public void callback(PackageResponse response) {
                System.out.println(response.getData());
            }
        });

    }


    public void loop(String url, Long id, ResponseCallback responseCallback) {
        String url_ = getUrl(url);
        String tmpUrl = (id != null && id >= 0) ? url_ +"?id="+ id : url_;
        HttpGet request = new HttpGet(tmpUrl);
        client.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse httpResponse) {
                Long lastId = id;
                try {
                    HttpEntity entity = httpResponse.getEntity();
                    String jsonString = EntityUtils.toString(entity, Charset.forName("UTF-8"));

                    if (jsonString != null && !jsonString.isEmpty()) {
                        PackageResponse response = JSON.parseObject(jsonString, PackageResponse.class);
                        responseCallback.callback(response);
                        lastId = response.getLastId();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    loop(url_, lastId,responseCallback);
                }
            }

            @Override
            public void failed(Exception e) {
                loop(url_, id, responseCallback);
            }

            @Override
            public void cancelled() {
                loop(url_, id, responseCallback);
            }
        });


    }

    private String getUrl(String url) {
        int indexOf = url.indexOf("?");
        if (indexOf != -1) {
            return url.substring(0, indexOf);
        }
        return url;
    }

    @Override
    public void close() {
        try {
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
